<template>
  <div class="register-container">
    <div class="register-card">
      <h2 class="register-title">用户注册</h2>
      <el-form :model="registerForm" ref="registerFormRef" :rules="registerRules" class="register-form">
        <el-form-item prop="tenant_code">
          <el-select v-model="registerForm.tenant_code" placeholder="请选择租户" class="tenant-select">
            <el-option
              v-for="item in tenants"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="username">
          <el-input v-model="registerForm.username" placeholder="用户名">
            <template #prefix>
              <span class="el-icon-user"></span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="registerForm.password" placeholder="密码" type="password">
            <template #prefix>
              <span class="el-icon-lock"></span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input v-model="registerForm.confirmPassword" placeholder="确认密码" type="password">
            <template #prefix>
              <span class="el-icon-lock"></span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleRegister" style="width: 100%">注册</el-button>
        </el-form-item>
        <div class="login-options">
          <router-link to="/login" class="login-link">返回登录</router-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'

export default {
  name: 'Register',
  setup() {
    const router = useRouter()
    const store = useStore()
    const registerFormRef = ref(null)
    const loading = ref(false)
    const tenants = ref([])
    
    const registerForm = reactive({
      username: '',
      password: '',
      confirmPassword: '',
      tenant_code: 'default'
    })
    
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (registerForm.confirmPassword !== '') {
          registerFormRef.value.validateField('confirmPassword')
        }
        callback()
      }
    }
    
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== registerForm.password) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }
    
    const registerRules = {
      tenant_code: [
        { required: true, message: '请选择租户', trigger: 'change' }
      ],
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' },
        { validator: validatePass, trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        { validator: validatePass2, trigger: 'blur' }
      ]
    }
    
    // 获取租户列表
    const fetchTenants = async () => {
      try {
        const tenantsData = await store.dispatch('fetchAvailableTenants');
        if (tenantsData && tenantsData.length > 0) {
          tenants.value = tenantsData;
          
          // 如果有租户，默认选择第一个
          registerForm.tenant_code = tenants.value[0].code;
        } else {
          // 如果没有获取到租户，使用默认租户
          tenants.value = [{ code: 'default', name: '默认租户' }];
          registerForm.tenant_code = 'default';
        }
      } catch (error) {
        console.error('获取租户列表失败', error);
        // 如果获取租户失败，添加默认租户
        tenants.value = [{ code: 'default', name: '默认租户' }];
        registerForm.tenant_code = 'default';
      }
    }
    
    onMounted(() => {
      fetchTenants()
    })
    
    const handleRegister = () => {
      registerFormRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true;
          try {
            const userData = {
              username: registerForm.username,
              password: registerForm.password,
              tenant_code: registerForm.tenant_code
            };
            
            const result = await store.dispatch('register', userData);
            
            if (result) {
              ElMessage.success('注册成功，请登录');
              router.push('/login');
            }
          } catch (error) {
            ElMessage.error(error.message || '注册失败，请重试');
          } finally {
            loading.value = false;
          }
        }
      });
    }
    
    return {
      registerFormRef,
      registerForm,
      registerRules,
      loading,
      tenants,
      handleRegister
    }
  }
}
</script>

<style scoped>
.register-container {
  height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f0f2f5;
  background-image: linear-gradient(to right, #3a7bd5, #00d2ff);
}

.register-card {
  width: 400px;
  padding: 40px;
  border-radius: 8px;
  background-color: white;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.register-title {
  text-align: center;
  margin-bottom: 30px;
  color: #409EFF;
  font-weight: bold;
}

.register-form {
  width: 100%;
  max-width: 400px;
}

.tenant-select {
  width: 100%;
}

.login-options {
  margin-top: 15px;
  text-align: center;
}

.login-link {
  font-size: 14px;
  color: #409eff;
  text-decoration: none;
}

.login-link:hover {
  text-decoration: underline;
}
</style> 